package com.example.internet;

import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.internet.bean.WeatherBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private ProgressBar progressBar;
    private EditText editTextTextPersonName;
    private TextView show;

    private String title_url = "http://api.help.bj.cn/apis/weather?id=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        progressBar = findViewById(R.id.progressBar);
        editTextTextPersonName = findViewById(R.id.editTextTextPersonName);
        show = findViewById(R.id.textView2);
    }

    public void download(View view) {
        /*textView.setText("下载开始");
        new Thread(() -> {
            try {
                Thread.sleep(3000);
//                Toast.makeText(MainActivity.this, "onclick", Toast.LENGTH_SHORT).show();
                Log.i("TAG", "download: ");
//                不能更新界面
                textView.setText("下载完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();*/

        MyDownLoadTask myDownLoadTask = new MyDownLoadTask();
        try {
            myDownLoadTask.execute(new URL("http://www.baidu.com"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }

    public void getWeather(View view) {
        //使用异步任务请求天气

        GetWeather getWeather = new GetWeather();
        String cityCode = editTextTextPersonName.getText().toString();
        try {
            if (cityCode.isEmpty()) {
                cityCode = "101060101";
            }
            getWeather.execute(new URL(title_url + cityCode));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }

    private class GetWeather extends AsyncTask<URL, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            1. 获得返回数据
//            2. 更新界面上
            WeatherBean weatherBean = JSON.parseObject(s, WeatherBean.class);
            String city = weatherBean.getCity();
            String humidity = weatherBean.getHumidity();
            String wd = weatherBean.getWd();
            String result = "城市：" + city + "\n" +
                    "湿度：" + humidity + "\n" +
                    "风向：" + wd;
            show.setText(result);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(URL... urls) {
//            1. 新建连接
            HttpURLConnection conn = null;
            String s = null;
            String temps = "";
//            2. 获得链接
            try {
                conn = (HttpURLConnection) urls[0].openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
//            3. 请求数据
                conn.connect();
                if (conn.getResponseCode() == 200) {
//            4. 解析数据
                    InputStream inputStream = conn.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    s = bufferedReader.readLine();
                    while (s != null) {
                        temps += s;
                        s = bufferedReader.readLine();
                    }
                    bufferedReader.close();
                    inputStream.close();
                }
//            5. 关闭连接
                conn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
//            6. 返回数据
            return temps;
        }
    }


    private class MyDownLoadTask extends AsyncTask<URL, Integer, String> {

        @Override
        protected String doInBackground(URL... urls) {
            new Thread(() -> {
                try {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(300);
                        publishProgress(i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            return null;
        }

        //在任务开始前执行
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setProgress(0);
            textView.setText("开始下载");
        }

        //在任务结束后执行
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("TAG", "下载完成");
            textView.setText("下载完成");
            progressBar.setProgress(0);
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
        }
    }

}